package mmc.gl;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import mmc.cell.ClientCell;
import mmc.cell.ClientCellBunch;

import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.SharedDrawable;

public class BackgroundLoader implements Runnable{

	private SharedDrawable sharedDrawable;
	private volatile boolean running = true;
	private List<ClientCell> cellsToMaintain = Collections.synchronizedList(new LinkedList<ClientCell>());
	private List<ClientCell> cellsToAdd = Collections.synchronizedList(new LinkedList<ClientCell>());
	private List<ClientCell> cellsToRemove = Collections.synchronizedList(new LinkedList<ClientCell>());
	
	public BackgroundLoader(SharedDrawable sharedDrawable) {
		this.sharedDrawable = sharedDrawable;
		new Thread(this,"BackgroundLoader").start();
	}

	@Override
	public void run() {
		try {
			sharedDrawable.makeCurrent();
			
			while(running){
				
				while(!cellsToAdd.isEmpty())
					cellsToMaintain.add(cellsToAdd.remove(0));
				
				while(!cellsToRemove.isEmpty())
					cellsToMaintain.remove(cellsToRemove.remove(0));
				
				for(ClientCell c : cellsToMaintain){
					c.updateBuffers();
				}
				
				GL11.glFlush();
				
				if(ClientCellBunch.cellBunch.clearLoad()==0){
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
			
			sharedDrawable.releaseContext();
			sharedDrawable.destroy();
		} catch (LWJGLException e) {
			throw new RuntimeException("Exception in BackgroundLoader: "+e.getMessage(),e);
		}
	}

	public void quit(){
		running = false;
	}
	
	public void addCell(ClientCell c){
		cellsToAdd.add(c);
	}
	
	public void removeCell(ClientCell c){
		cellsToRemove.add(c);
	}
}
